import ProTable, {ActionType} from '@ant-design/pro-table';
import {useRef, useState} from 'react';
import {defaultPagination, paginationTool} from '@/utils/util';
import {useMount, useRequest} from 'ahooks';
import {Button, Input, message, Modal, Popconfirm} from 'antd';
import {PlusOutlined, QuestionCircleOutlined} from '@ant-design/icons';

import {BetaSchemaForm, ProFormColumnsType, ProFormInstance} from '@ant-design/pro-form';
import {ColumnsType} from 'antd/lib/table';
import {
  editRole,
  navDistribution,
  roleDistributionList,
  roleDistributionNav,
  roleFindByPageList,
  roleNavDistributionList
} from "@/services/ant-design-pro/permession";
import {findByDataCategoryTreeList, findByDataMenuTreeList} from "@/services/ant-design-pro/menu";


interface DataType {
  name: string;
  address: string;
}

const columns1: ColumnsType[any] = [
  {
    title: 'Image',
    dataIndex: 'image',
    valueType: "image",
    fieldProps: {
      width: '30px'
    }

  },
  {
    title: 'Name',
    dataIndex: 'name',

  }
];
const columns2: ColumnsType[any] = [
  {
    title: 'Name',
    dataIndex: 'name',

  }
];


// rowSelection object indicates the need for row selection
const rowSelection = {
  onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
    console.log ( `selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows );
  },
  getCheckboxProps: (record: DataType) => ({
    disabled: record.name === 'Disabled User', // Column configuration not to be checked
    name: record.name,
  }),
};
const cloneTbale = () => {
  const actionRef = useRef<ActionType> ();
  const formRef = useRef<ProFormInstance<API.Agent>> ();
  const [editDialg, setEditDialg] = useState ( false );
  const [editPermissonDialg, setEditPermissonDialg] = useState ( false );
  const [editPermissonRoleDialg, setEditPermissonRoleDialg] = useState ( false );


  const [selectedKeys, setSelectedKeys] = useState<number[]> ( [] );
  const [selectedRoleKeys, setSelectedRoleKeys] = useState<number[]> ( [] );
  const [agents, setAgents] = useState<API.Agent> ( {} );
  const columns = [
    {
      title: '编号',
      dataIndex: 'index',
      key: 'index',
      valueType: 'indexBorder',
    },
    {
      title: '自动编号',
      dataIndex: 'id',
      key: 'id',
      search: false,
      hideInTable: true,
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '操作',
      width: '264px',
      key: 'option',
      valueType: 'option',
      render: (_: any, row: API.Agent, index: number, action: any) => [
        <a
          key="link"
          onClick={(a) => {
            console.log ( row );
            setAgents ( row );
            editDialogInfo ( row, index );
          }}
        >
          编辑
        </a>,
        <a
          key="link"
          onClick={(a) => {
            console.log ( row );
            fetchByAgentDistributionList ( row?.id ).then ( res => {
              setSelectedKeys ( res?.data )
            } )

            setAgents ( row );
            editDialogPermessionInfo ( row, index );
          }}
        >
          前端权限
        </a>, <a
          key="link"
          onClick={(a) => {
            console.log ( row );
            fetchByRoleDistributionList ( row?.id ).then ( res => {
              setSelectedRoleKeys ( res?.data )
            } )

            setAgents ( row );
            editRoleDialogPermessionInfo ( row, index );
          }}
        >
          后台权限
        </a>,
        <Popconfirm title="Are you sure？" icon={<QuestionCircleOutlined style={{color: 'red'}}/>}>
          <a href="#">Delete</a>
        </Popconfirm>
      ],
    },
  ];

  const columnDialog: ProFormColumnsType<API.Agent>[] = [
    {
      title: '基本信息',
      valueType: 'group',
      columns: [
        {
          title: 'id',
          dataIndex: 'id',
          key: 'id',

          formItemProps: {
            hidden: true,
          },
        },
        {
          title: '名称',
          dataIndex: 'name',
          key: 'name',
          width: 'md',
          formItemProps: {
            rules: [
              {
                required: true,
                message: '此项为必填项',
              },
            ],
          },
        }
      ],
    },
  ];
  const [columnDialogs, setColumnDialogs] = useState ( columnDialog );

  const [pagination, setPagination] = useState<API.Pagination> ( defaultPagination () );
  const {
    run: fetchByPageList,
    refresh,
    data: dataList,
    loading,
  } = useRequest ( roleFindByPageList, {
    debounceWait: 100,
    manual: true,
  } );
  const {
    run: fetchByDataMenuTreeList,
    refresh: refreshTree,
    data: dataListTree,
    loading: loadingTree,
  } = useRequest ( findByDataCategoryTreeList, {
    debounceWait: 100,
    manual: true,
  } );
  const {
    runAsync: fetchByAgentDistributionList,
    refresh: refreshAgentDistributionList,
    data: dataListAgentDistributionList,
    loading: loadingAgentDistributionList,
  } = useRequest ( roleNavDistributionList, {
    debounceWait: 100,
    manual: true,
  } );

  const {
    runAsync: fetchByRoleDistributionList,
    data: dataListRoleDistributionList,
  } = useRequest ( roleDistributionList, {
    debounceWait: 100,
    manual: true,
  } );

  const {
    runAsync: fetchByDataMenuPerTreeList,
    data: dataMenuList,
  } = useRequest ( findByDataMenuTreeList, {
    debounceWait: 100,
    manual: true,
  } );
  //
  useMount ( () => {
    fetchByPageList ();
  fetchByDataMenuTreeList ()
   fetchByDataMenuPerTreeList ()

  } );

  function hideEditDialg() {
    setAgents ( {...agents, id: 0} );
    formRef.current?.resetFields ();
    formRef?.current?.setFieldsValue ( {id: 0} );
    setEditDialg ( false );
  }

  function openEditDialg() {
    // @ts-ignore
    setAgents ( {
      id: 0,
      name: ''
    } );
    formRef.current?.resetFields ();
    formRef?.current?.setFieldsValue ( {name: '', id: 0, nameUg: '', price: 0, level: 0} );
    setEditDialg ( true );
  }

  function editDialogInfo(row: API.Agent, index: number) {
    setAgents ( row );
    console.log ( 'editDialogInfo', row );
    formRef?.current?.setFieldsValue ( row );
    //  formRef?.current?.setFieldsValue ( {id: row.id}  );
    console.log ( 'editDialogInfo', formRef?.current?.getFieldsValue () );
    setEditDialg ( true );
  }


  //editDialogPermessionInfo
  function editDialogPermessionInfo(row: API.Agent, index: number) {
    setAgents ( row );
    console.log ( 'editDialogInfo', row );
    setEditPermissonDialg ( true );
    // @ts-ignore
    setSelectedKeys ( dataListAgentDistributionList?.data )
  }

//editPermissonRoleDialg
  //editDialogPermessionInfo
  function editRoleDialogPermessionInfo(row: API.Agent, index: number) {
    setAgents ( row );
    console.log ( 'editDialogInfo', row );
    setEditPermissonRoleDialg ( true );

  }

  return (
    <div>

      <Modal title={agents.name} open={editPermissonRoleDialg} onCancel={() => {
      //  setEditPermissonRoleDialg ( false )
        setEditPermissonDialg(false)
        // @ts-ignore
        setAgents ( {
          id: 0,
          name: ''
        } )

      }} onOk={(e => {
        let param = {
          ids: selectedRoleKeys,
          roleId: agents?.id
        }

        roleDistributionNav ( param ).then ( res => {
          console.log ( res )
          if (res.status == 200) {
            setEditDialg ( false )
            // @ts-ignore
            setAgents ( {
              id: 0,
              name: ''
            } )
            setSelectedRoleKeys ( [] )
            message.success ( "成功" )
          } else {
            message.error ( "失败" )
          }
        } )
      })} >
        <>
          <ProTable toolBarRender={false} rowKey="id" pagination={false} search={false}
                    rowSelection={{
                      selectedRowKeys: selectedRoleKeys,
                      type: 'checkbox',
                      onChange: (selectedKeys: any, info: any) => {
                        setSelectedRoleKeys ( selectedKeys )
                      }
                    }}
                    columns={columns2}
                    actionRef={actionRef}
                    dataSource={dataMenuList?.data}

          />

        </>
      </Modal>


      <Modal title={agents.name} open={editPermissonRoleDialg} onCancel={() => {
        setEditPermissonRoleDialg ( false )
        // @ts-ignore
        setAgents ( {
          id: 0,
          name: ''
        } )
      }} onOk={(e => {
        let param = {
          ids: selectedRoleKeys,
          roleId: agents?.id
        }
        console.log ( param )
        roleDistributionNav ( param ).then ( res => {
          console.log ( res )
          if (res.status == 200) {
            setEditPermissonRoleDialg ( false )
            // @ts-ignore
            setAgents ( {
              id: 0,
              name: ''
            } )
            setSelectedRoleKeys ( [] )
            message.success ( "成功" )
          } else {
            message.error ( "失败" )
          }
        } )
      })}>
        <>
          <ProTable toolBarRender={false} rowKey="id" pagination={false} search={false}
                    rowSelection={{
                      selectedRowKeys: selectedRoleKeys,
                      type: 'checkbox',
                      onChange: (selectedKeys: any, info: any) => {
                        setSelectedRoleKeys ( selectedKeys )
                      }
                    }}
                    columns={columns2}
                    actionRef={actionRef}
                    dataSource={dataMenuList?.data}

          />

        </>
      </Modal>

      <Modal title={agents.name} open={editPermissonDialg} onCancel={() => {
        setEditPermissonDialg ( false )
        // @ts-ignore
        setAgents ( {
          id: 0,
          name: ''
        } )
      }} onOk={(e => {
        let param = {
          ids: selectedKeys,
          roleId: agents?.id
        }
        console.log ( param )
        navDistribution ( param ).then ( res => {
          console.log ( res )
          if (res.status == 200) {
            setEditPermissonDialg ( false )
            // @ts-ignore
            setAgents ( {
              id: 0,
              name: ''
            } )
            setSelectedKeys ( [] )
            message.success ( "成功" )
          } else {
            message.error ( "失败" )
          }
        } )
      })}>
        <>
          <ProTable toolBarRender={false} rowKey="id" pagination={false} search={false}
                    rowSelection={{
                      selectedRowKeys: selectedKeys,
                      type: 'checkbox',
                      onChange: (selectedKeys: any, info: any) => {
                        console.log ( 'onChange', selectedKeys, info )
                        setSelectedKeys ( selectedKeys )
                      }
                    }}
                    columns={columns1}
                    actionRef={actionRef}
                    dataSource={dataListTree?.data}

          />

        </>
      </Modal>
      <BetaSchemaForm<API.Agent>
        formRef={formRef}
        initialValues={agents}
        onCancel={() => setEditDialg ( false )}
        onVisibleChange={setEditDialg}
        title="产品分类"
        visible={editDialg}
        layoutType="ModalForm"
        columns={columnDialogs}
        // @ts-ignore
        onFinish={async (values) => {
          // @ts-ignore
          //   values.id=category.id;
          //setCategory({...category,...values})

          //  values = Object.assign ( category, values )
          console.log ( agents, values );
          return new Promise<Boolean> ( (resolve, reject) => {
            editRole ( values )
              .then ( () => {
                message.success ( '操作成功' );
                setEditDialg ( false );
                refresh ();
                resolve ( true );
              } )
              .catch ( () => {
                message.success ( '操作失败' );
                reject ( false );
              } );
          } );
        }}
      />
      <ProTable
        search={false}

        onDataSourceChange={(d) => {
          console.log ( 'onDataSourceChange', d );
        }}
        onLoad={(d) => {
          // 数据加载完操作
          console.log ( 'onDataSourceChange', d );
        }}
        toolBarRender={() => [
          <Button
            onClick={() => {
              formRef.current?.resetFields ();
              openEditDialg ();
            }}
            key="button"
            icon={<PlusOutlined/>}
            type="primary"
          >
            新建
          </Button>,
        ]}
        dataSource={dataList?.data?.list}
        loading={loading}
        pagination={paginationTool ( pagination, dataList?.data?.total, (data1: API.Pagination) => {
          setPagination ( data1 );

          fetchByPageList ( {...pagination} );
        } )}
        search={false}
        cardBordered={true}
        columns={columns}
      ></ProTable>
    </div>
  );
};

export default cloneTbale;
